import { defineStore } from "pinia"
import { reqLogin, reqLogOut, reqUserInfo } from '@/api/user.ts'
import { MyInfo, ReqLoginParams } from '@/types/user'
const useUserStore = defineStore('user', {
  state: ():MyInfo => {
    return {
      token: window.localStorage.getItem('token') || '',
      userInfo: {
        name: '',
      }
    }
  },

  actions: {
    async login(params: ReqLoginParams) {
      const res = await reqLogin(params)
      if(res.code === 200){
        this.token = res.data.token as string
        window.localStorage.setItem('token', res.data.token as string)
        return Promise.resolve(true)
      } else {
        return Promise.resolve(false)
      }
    },
    async getUserInfo() {
      const res = await reqUserInfo()
      if(res.code === 200){
        this.userInfo = res.data
        return Promise.resolve(true)
      } else {
        return Promise.reject(res.message)
      }
    },
    async logOut() {
      const res = await reqLogOut()
      if(res.code === 200){
        this.userInfo = {name:''}
        this.token = ''
        window.localStorage.removeItem('token')
        return Promise.resolve(true)
      } else{
        return Promise.resolve(false)
      }
    }
  }
})

export { useUserStore }
